var express = require('express');
var router = express.Router();
const {User} = require('../models')
const {success,failure} = require('../util/requestResult')
const {NotFoundError,BadRequestError,UnauthorizedError} = require('../util/errors')

router.post('/',async function(req,res,next){
    try {
        let {account,password} = req.body
        let user = await User.findOne({where:{account}})
        if(user)
        {
            if(user.password == password){
                res.cookie("account",account,{domain:'localhost',maxAge:6000,path:'/'})
                res.cookie("password",password,{domain:'localhost',maxAge:6000,path:'/'})
                req.session.account = account
                req.session.password = password
                success(res,'登录成功',{user})
            }
            else{
                throw new UnauthorizedError("密码错误");
            }
        }
        else{
            throw new NotFoundError("未查询到此账号"); 
        }
    } catch (error) {
        failure(res,error)
    }

})


router.get('/get-session', (req, res) => {
    const account = req.session.account; // 获取session数据
    const password = req.session.password; // 获取session数据
    if(account && password)
        success(res,'获取会话成功',{account,password})
    else
        res.status(200).json({
            code: 0,
            message: '无会话信息'
        })
});

module.exports = router